const jwt = require("../util/jwt");
const config = require("../config/config");
const { AppError } = require("./errorHandler");
const User = require("../model/system/User");

// 验证JWT token
const authenticateToken = async (req, res, next) => {
  try {
    const authHeader = req.headers["authorization"];
    const token = authHeader && authHeader.split(" ")[1]; // Bearer TOKEN
    if (!token) {
      return next(new AppError("token不存在", 401));
    }
    const decodeToken = await jwt.verify(token, config.jwt.secret);
    req.user = await User.findById(decodeToken.userId);
    console.log(req.user, "req.user");
    next();
  } catch (error) {
    next(new AppError("token验证失败", 401));
  }
};

// 验证用户角色
const authorize = (...roles) => {
  return (req, res, next) => {
    if (!req.user) {
      return next(new AppError("User not authenticated", 401));
    }

    if (!roles.includes(req.user.role)) {
      return next(new AppError("Insufficient permissions", 403));
    }

    next();
  };
};

// 可选身份验证（不强制要求token）
const optionalAuth = (req, res, next) => {
  try {
    const authHeader = req.headers["authorization"];
    const token = authHeader && authHeader.split(" ")[1];

    if (token) {
      jwt.verify(token, config.jwt.secret, (err, user) => {
        if (!err) {
          req.user = user;
        }
      });
    }
    next();
  } catch (error) {
    next();
  }
};

module.exports = {
  authenticateToken,
  authorize,
  optionalAuth,
};
